package com.cloud.user.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cloud.platform.IDao;
import com.cloud.platform.util.Constants;
import com.cloud.platform.util.StringUtil;
import com.cloud.user.model.User;

@Component
public class UserService {

	@Autowired
	private IDao dao;
	
	/**
	 * save user's sign
	 * 
	 * @param userId
	 * @param sign
	 */
	public void saveUserSign(String userId, String sign) {
		
		if(StringUtil.isNullOrEmpty(userId)) {
			return;
		}
		
		User user = (User) dao.getObject(User.class, userId);
		user.setSign(sign);
		
		dao.saveObject(user);
	}
	
	/**
	 * get user's sign
	 * 
	 * @param userId
	 * @return
	 */
	public String getUserSign(String userId) {
		
		User user = (User) dao.getObject(User.class, userId);
		
		if(user != null) {
			return user.getSign();
		}
		
		return "";
	}
	
	/**
	 * get user's password
	 * 
	 * @param userId
	 * @return
	 */
	public String getUserPassword(String userId) {
		
		User user = (User) dao.getObject(User.class, userId);
		
		if(user != null) {
			return user.getPassword();
		}
		
		return "";
	}
	
	/**
	 * check username and password valid for login
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public User checkLogin(String username, String password) {
		if(StringUtil.isNullOrEmpty(username, password)) {
			return null;
		}
		
		String hql = "from User where username = ? and password = ?";
		
		List list = dao.getAllByHql(hql, new Object[] { username, password });
		
		if(list != null && !list.isEmpty()) {
			return (User) list.get(0);
		}
		
		return null;
	}
	
	/**
	 * save user info for register
	 * 
	 * @param username
	 * @param password
	 * @param email
	 */
	public void register(String username, String password, String email) {
		
		User user = new User();
		user.setId(Constants.getID());
		user.setUsername(username);
		user.setPassword(password);
		user.setEmail(email);
		
		dao.saveObject(user);
	}
	
	/**
	 * change user's password
	 * 
	 * @param userId
	 * @param newPassword
	 */
	public void changePassword(String userId, String newPassword) {
		
		if(StringUtil.isNullOrEmpty(userId, newPassword)) {
			return;
		}
		
		User user = (User) dao.getObject(User.class, userId);
		user.setPassword(newPassword);
		
		dao.saveObject(user);
	}
}
